package com.demo.config;

import com.demo.commons.BaseConsts;
import com.demo.exetion.MainExection;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.SneakyThrows;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;

@Component
@Order(1)
public class MyGlobaleFilter implements GlobalFilter, Ordered {

    private AntPathMatcher pathMatcher=new AntPathMatcher();
    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<String> keys = exchange.getRequest().getHeaders().get(BaseConsts.TOKEN_KEY);
        String token = "";
        if(keys != null && keys.size() > 0) token = keys.get(0);
        System.out.println(token);
        //拿出url判断是否需要校验登录
        String uri=exchange.getRequest().getPath().toString();
        List<String> urls = BaseConsts.getUrls();
        for (String url : urls) {
            if (pathMatcher.match(url,uri)){
                return chain.filter(exchange);
            }
        }
        //解析取出的token通过异常捕获来确定是否有问题
        try {
            JwtTemplate.parseJwt(token);
        } catch(ExpiredJwtException e) {
            throw new MainExection(403, "Token过期");
        } catch(Exception e) {
            throw new MainExection(403, "解析失败");
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
